package componentes;

import java.awt.Color;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.media.opengl.GL;

import properties.Config;
import transformaciones.TAfin;
import figuras.BSplines;
import figuras.PuntoVector;
import figuras.malla.MallaPorSplineYRevolucion;

public class Componente3DRevolucion extends Componente3D {

	public Componente3DRevolucion(GL gl, File file) throws IOException,
			IndexOutOfBoundsException, FileNotFoundException {
		this.gl = gl;
		matriz = this.getMatriz();
		this.cargar(file);
	}

	public Componente3DRevolucion(MallaPorSplineYRevolucion malla,
			ArrayList<BSplines> bsplines, GL gl) {
		super();
		this.malla = malla;
		this.bsplines = bsplines;
		color = Color.GREEN;
		this.gl = gl;
		matriz = new TAfin(this.gl);
	}

	public void cargar(File file) throws FileNotFoundException, IOException,
			IndexOutOfBoundsException {
		DataInputStream ois;
		ois = new DataInputStream(new BufferedInputStream(new FileInputStream(
				file)));
		int red = ois.readInt();
		int green = ois.readInt();
		int blue = ois.readInt();
		color = new Color(red, green, blue);
		ArrayList<PuntoVector> puntosControl = new ArrayList<PuntoVector>();
		int numPuntos = ois.readInt();
		for (int i = 0; i < numPuntos; i++) {
			double x = ois.readDouble();
			double y = ois.readDouble();
			double z = ois.readDouble();
			puntosControl.add(new PuntoVector(x, y, z, 1));
		}
		ois.close();
		this.bsplines = new ArrayList<BSplines>();
		BSplines b = new BSplines();
		b.setPuntosControl(puntosControl);
		b.perfilaSpline();
		bsplines.add(b);
		Config config = Config.getInstance();
		double radianes = config.getDouble("receptaculo.radianes.revolucion");
		int pasos = config.getInteger("receptaculo.pasos.revolucion");
		malla = new MallaPorSplineYRevolucion(b,
				radianes,pasos,false);
	}

	public void guardar(File file) throws IOException, FileNotFoundException,
			java.lang.IndexOutOfBoundsException {
		DataOutputStream oos = null;
		oos = new DataOutputStream(new BufferedOutputStream(
				new FileOutputStream(file)));
		oos.writeInt(color.getRed());
		oos.writeInt(color.getGreen());
		oos.writeInt(color.getBlue());
		ArrayList<PuntoVector> puntosControl = this.bsplines.get(0)
				.getPuntosControl();
		oos.writeInt(puntosControl.size());
		for (PuntoVector p : puntosControl) {
			oos.writeDouble(p.getX());
			oos.writeDouble(p.getY());
			oos.writeDouble(p.getZ());
		}
		oos.close();
	}
}
